import { Button, Form, Input, Rate, Toast, Uploader } from 'react-vant';
import './CommentAdd.css';
import commentApi from '@/apis/commentApi';
import { useLocation, useNavigate } from 'react-router-dom';

const CommentAdd: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation();
  const navigate = useNavigate();
  const gid: string = new URLSearchParams(location.search).get('gid') ?? '-1';
  const odid: string = new URLSearchParams(location.search).get('odid') ?? '-1';

  const onFinish = async (values: any) => {
    console.log(values);
    const formData = new FormData();
    for (let key in values) {
      if (values[key] instanceof Array) {
        for (let i = 0; i < values[key].length; i++) {
          formData.append(key, values[key][i].file);
        }
      } else {
        formData.append(key, values[key]);
      }
    }
    formData.append('goodId', gid);
    formData.append('orderDetailId', odid);
    const res = await commentApi.addComment2(formData);
    if (res.status >= 0) {
      Toast.success('发布成功');
      setTimeout(() => {
        navigate(-1);
      }, 200);
    }
  };

  return (
    <>
      <Form form={form} onFinish={onFinish} initialValues={{ content: '', rate: 5, image: [] }}>
        <Form.Item
          rules={[{ required: true, message: '请填写评论内容' }]}
          name="content"
          label="内容"
        >
          <Input.TextArea placeholder="多行输入" />
        </Form.Item>
        <Form.Item name="rate" label="评分">
          <Rate></Rate>
        </Form.Item>
        <Form.Item name="image" label="图片">
          <Uploader accept="image" />
        </Form.Item>
        <div className="right-text padding12">
          <Button type="primary" onClick={() => form.submit()}>
            发布
          </Button>
        </div>
      </Form>
    </>
  );
};

export default CommentAdd;
